import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserInfoStore } from '@/stores/userInfo'

const routes: Array<RouteRecordRaw> = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue')
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('@/views/Register.vue')
    },
    {
        path: '/',
        component: () => import('@/views/Layout.vue'),
        children: [
            { path: '', redirect: '/user' },
            { path: 'user', name: 'User', component: () => import('@/views/user/UserList.vue') },
            { path: 'hotel', name: 'Hotel', component: () => import('@/views/hotel/HotelList.vue') },
            { path: 'room', name: 'Room', component: () => import('@/views/room/RoomList.vue') },
            { path: 'order', name: 'Order', component: () => import('@/views/order/OrderList.vue') },
            { path: 'review', name: 'Review', component: () => import('@/views/review/ReviewList.vue') },
            { path: 'profile', name: 'Profile', component: () => import('@/views/user/UserProfile.vue') }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const userInfoStore = useUserInfoStore()
    // 允许直接访问登录页和注册页
    if (to.path === '/login' || to.path === '/register') {
        next()
        return
    }
    // 未登录跳转到登录页
    if (!userInfoStore.userInfo) {
        next('/login')
        return
    }
    next()
})

export default router
